<!-- src/components/admin/course-modal.vue -->
<template>
  <u-popup :show="C.showModal.value" mode="center" :round="10">
    <view class="vbox popup-container">
      <view class="popup-header">
        <text>{{
          C.modalMode.value === "edit" ? "编辑课程" : "添加课程"
        }}</text>
        <view class="fill"></view>
        <u-icon
          name="close"
          @click="C.closePopup()"
          size="18"
        ></u-icon>
      </view>
      <u-form :model="C.currentModel" ref="formRef">
        <u-form-item label="课程Logo" prop="logo">
          <view class="logo-preview-container">
            <!-- 显示已上传的图片预览 -->
            <view v-if="getFileListValue() && getFileListValue().length > 0" class="logo-preview-wrapper">
              <image 
                :src="getFileListValue()[0].url" 
                class="logo-preview"
                mode="aspectFill"
              />
            </view>
            <!-- 显示已存在的logo（编辑时） -->
            <view v-else-if="C.currentModel.logo && !getFileListValue().length" class="logo-preview-wrapper">
              <image 
                :src="C.formatFileUrl(C.currentModel.logo)" 
                class="logo-preview"
                mode="aspectFill"
              />
            </view>
            <!-- 上传组件 -->
            <up-upload 
              :fileList="getFileListValue()"
              @afterRead="handleFileRead" 
              @delete="handleFileDelete"
              :maxCount="1">
            </up-upload>
          </view>
        </u-form-item>
        
        <u-form-item label="课程名称" prop="name">
          <u-input
            v-model="C.currentModel.name"
            placeholder="输入课程名称"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="课程描述" prop="desc">
          <u-input
            v-model="C.currentModel.desc"
            placeholder="输入课程描述"
            type="textarea"
            :auto-height="true"
          ></u-input>
        </u-form-item>

        <view class="hbox">
          <u-button
            type="default"
            @click="C.closePopup()"
            text="取消"
          ></u-button>
          <u-button
            type="primary"
            @click="C.handleSubmit()"
            :text="C.modalMode.value === 'edit' ? '保存' : '添加'"
          ></u-button>
        </view>
      </u-form>
    </view>
  </u-popup>
</template>

<script setup>
import C from "@/js/admin/course.js";
import "jbecool/jbecool.uniapp.min.js";

// 获取文件列表值
const getFileListValue = () => {
  try {
    const courseId = C.currentModel.courseId || -1;
    if (C.fileList && 
        C.fileList[courseId] && 
        C.fileList[courseId].logo && 
        C.fileList[courseId].logo.value) {
      return C.fileList[courseId].logo.value;
    }
    return [];
  } catch (e) {
    console.warn('获取文件列表时出错:', e);
    return [];
  }
};

// 处理文件读取
const handleFileRead = async (event) => {
  try {
    const courseId = C.currentModel.courseId || -1;
    
    // 确保文件列表结构存在
    if (!C.fileList[courseId]) {
      C.fileList[courseId] = {};
    }
    if (!C.fileList[courseId].logo) {
      C.fileList[courseId].logo = { value: [] };
    }
    
    // 添加文件到列表
    C.fileList[courseId].logo.value.push({
      ...event.file,
      status: 'uploading',
      message: '上传中',
    });
    
    // 上传文件
    const im = await J.callUploadAsync(event.file.url, { keep: false, override: false });
    
    if (im.success) {
      // 更新文件状态
      const fileIndex = C.fileList[courseId].logo.value.length - 1;
      C.fileList[courseId].logo.value[fileIndex] = {
        ...event.file,
        status: 'success',
        message: '',
        url: C.formatFileUrl(im.data.filename),
      };
      
      // 更新当前模型的logo字段
      C.currentModel.logo = im.data.filename;
    } else {
      // 移除上传失败的文件
      C.fileList[courseId].logo.value.pop();
      uni.showToast({ title: '上传失败: ' + im.msg, icon: 'none' });
    }
  } catch (error) {
    console.error('文件上传出错:', error);
    // 移除上传出错的文件
    const courseId = C.currentModel.courseId || -1;
    if (C.fileList[courseId] && C.fileList[courseId].logo) {
      C.fileList[courseId].logo.value.pop();
    }
    uni.showToast({ title: '上传出错', icon: 'none' });
  }
};

// 处理文件删除
const handleFileDelete = (event) => {
  const courseId = C.currentModel.courseId || -1;
  if (C.fileList[courseId] && C.fileList[courseId].logo) {
    C.fileList[courseId].logo.value.splice(event.index, 1);
    // 清空当前模型的logo字段
    C.currentModel.logo = '';
  }
};
</script>

<style scoped>
.popup-container {
  padding: 20px;
  width: 80vw;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.fill {
  flex: 1;
}

.hbox {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.hbox u-button {
  flex: 1;
}

.logo-preview-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.logo-preview-wrapper {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  margin-bottom: 10px;
}

.logo-preview {
  width: 100%;
  height: 100%;
  display: block;
}
</style>